package com.enjoy.concurrent.ch4;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "enjoy")
public class ConditionCase {
    private static final Lock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {


        new Thread(() -> {
            try {
                log.info("加锁");
                lock.lock();
                log.info("await");
                condition.await();
                log.info("被唤醒了");
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            } finally {
                lock.unlock();
                log.info("解锁");
            }
        }, "t1").start();

        Thread.sleep(1000);

        new Thread(() -> {
            try {
                log.info("加锁");
                lock.lock();
                log.info("await");
                condition.await();
                log.info("被唤醒了");
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            } finally {
                lock.unlock();
                log.info("解锁");
            }
        }, "t2").start();

        Thread.sleep(1000);

        new Thread(() -> {
            try {
                log.info("加锁");
                lock.lock();
                condition.signalAll();
                log.info("唤醒wait的线程");
            } finally {
                lock.unlock();
                log.info("解锁");
            }
        }, "t3").start();

        Thread.sleep(1000);
    }
}
